import { Modal, configProvider } from 'ant-design-vue'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import store from '@/store'
// import router from '@/router'
let timeFn = new Date().getTime(); let dialogInstance
let allDialogInstance = []
export default (Vue) => {
  function dialog (component, modalProps, componentProps) {
    const _vm = this
    const FLAHISVUE = typeof component === 'string'
    modalProps = Object.assign({
      width: 600,
      maskClosable: false,
      centered: true,
      cancelText: '取消',
      okText: '确定',
      destroyOnClose: true,
      clickTime: 600,
      dialogClass: 'dragmodal dragBoxAifan' + Math.random().toString(36).substring(2)
    }, modalProps || {})
    if (!_vm || !_vm._isVue) {
      return
    }
    let dialogDiv = document.querySelector('body>div[type=dialog]')
    if (!dialogDiv) {
      dialogDiv = document.createElement('div')
      dialogDiv.setAttribute('type', 'dialog')
      document.body.appendChild(dialogDiv)
    }
    const handle = function (dialogCompoents, checkFunction, afterHandel) {
      if (checkFunction instanceof Function) {
        const res = checkFunction(dialogCompoents)
        if (res instanceof Promise) {
          res.then(c => {
            c && afterHandel()
          })
        } else {
          res && afterHandel()
        }
      } else {
        afterHandel()
      }
    }

    let componentObj = {
      // router,
      store,
      provide: {
        close: () => {
          dialogInstance.visible = false
          dialogInstance.$destroy()
        }
      },
      props: ['msg'],
      data () {
        return {
          visible: true,
          dragBox: 'dragBox',
          // 默认样式
          styleFill: {
            left: '50%',
            top: 100,
            bottom: 0,
            right: 0
          },
          // 鼠标摁下时的元素位置
          startOffset: { x: '', y: '' },
          // 鼠标摁下时的鼠标位置
          startPoint: { x: '', y: '' },
          oldoffsetHeight: ''
        }
      },
      mounted () {
        this.drag(this.visible)
      },
      methods: {
        handleClose () {
          let modalCallback = modalProps.ons
          handle(this, (modalCallback && modalCallback.onCancel) || (this.$refs._component && this.$refs._component.onCancel), () => {
            this.selfClose()
          })
        },
        handleOk () {
          let modalCallback = modalProps.ons
          if (new Date().getTime() - timeFn > (modalProps.clickTime)) {
            // 重新赋值时间
            timeFn = new Date().getTime()
            // 满足条件，执行函数
            handle(this, (modalCallback && modalCallback.onOK) || (this.$refs._component && (this.$refs._component.onOK || this.$refs._component.onOk)), () => {
              this.selfClose()
            })
          }
        },
        // 全部关闭弹窗
        modalAllClose () {
          let len = allDialogInstance.length
          while (len > 0) {
            len--
            allDialogInstance[len].visible = false
            // 动画执行完成销毁
            setTimeout(() => {
              allDialogInstance[len].$destroy()
              allDialogInstance.splice(len, 1)
            }, 300)
          }
        },
        // 单独关闭
        selfClose () {
          this.visible = false
          setTimeout(() => {
            this.$destroy()
          }, 300)
        },
        // 拖拽
        drag (visible) {
          let { title, move } = modalProps
          let { styleFill } = this
          if (!move) return false
          if (title && visible) {
            this.$nextTick(() => {
              this.contain = document.getElementsByClassName(modalProps.dialogClass)[0]
              let clientHeight = document.documentElement.clientHeight
              if (this.contain.clientHeight > clientHeight) {
                return
              }
              this.contain.style.width = typeof (modalProps.width) === 'number' ? modalProps.width + 'px' : modalProps.width
              this.contain.style.left = typeof (styleFill.left) === 'number' ? styleFill.left + 'px' : styleFill.left
              this.contain.style.top = typeof (styleFill.top) === 'number' ? styleFill.top + 'px' : styleFill.top
              this.contain.style.position = 'absolute'
              this.contain.style.marginLeft = -(modalProps.width / 2) + 'px'
              this.contain.addEventListener('mousedown', this.toTop, false)
              this.toTop()
              this.header = this.contain.getElementsByClassName('ant-modal-header')[0]
              this.header.style.cursor = 'all-scroll'
              this.oldoffsetHeight = this.contain.querySelector('.ant-modal-body').offsetHeight
              if (this.contain.offsetHeight > window.innerHeight) {
                this.contain.style.bottom = 0
              } else {
                this.contain.style.bottom = 'auto'
              }
              this.header.onmousedown = (e) => {
                this.down(e)
                document.body.onselectstart = () => false
                window.addEventListener('mousemove', this.move, false)
              }
              window.addEventListener('mouseup', this.removeUp, false)
            })
          }
        },
        // 摁下时的处理函数
        down (e) {
          let { contain } = this
          this.startPoint = {
            x: e.clientX,
            y: e.clientY
          }
          this.startOffset = {
            x: contain.offsetLeft,
            y: contain.offsetTop
          }
        },
        // 移动
        move (event) {
          let { contain, startOffset, startPoint } = this
          let newPoint = {
            x: event.clientX,
            y: event.clientY
          }
          let dis = {
            x: newPoint.x - (startPoint.x - startOffset.x),
            y: newPoint.y - (startPoint.y - startOffset.y)
          }
          contain.style.left = dis.x + 'px'
          contain.style.top = dis.y + 'px'
          const { top, left, right, bottom, width, height } = this.contain.getBoundingClientRect()
          contain.style.margin = 'unset'
          // 针对IE单独处理
          if (!!window.ActiveXObject || 'ActiveXObject' in window) {
            contain.style.margin = '0'
          }
          if (bottom > window.innerHeight) { this.contain.style.top = window.innerHeight - height - 20 + 'px' }
          if (top < 0) { this.contain.style.top = 20 + 'px' }
          if (right > window.innerWidth) { this.contain.style.left = window.innerWidth - width - 20 + 'px' }
          if (left < 0) { this.contain.style.left = 20 + 'px' }
        },
        removeMove () {
          window.removeEventListener('mousemove', this.move, false)
        },
        removeUp () {
          document.body.onselectstart = () => true
          this.removeMove()
        },
        toTop () {
          let autoIndexArr = document.getElementsByClassName('autoIndex')
          if (autoIndexArr.length < 1) return false
          let max = 0
          for (let i = 0; i < autoIndexArr.length; i++) {
            let zIndex = parseInt(autoIndexArr[i].style.zIndex || 1000)
            if (zIndex > max) max = zIndex
          }
          this.contain.style.zIndex = max + 1
        }

      },
      // 组件销毁
      destroyed () {
        this.removeMove()
        window.removeEventListener('mouseup', this.removeUp, false)
      },
      render: function (h) {
        const that = this
        const modalModel = modalProps && modalProps.model
        if (modalModel) {
          delete modalProps.model
        }
        // eslint-disable-next-line no-mixed-operators
        const ModalProps = Object.assign({}, modalModel && { model: modalModel } || {}, {
          ref: '_aifanMadal',
          attrs: Object.assign({
            title: '操作'
          }, {
            ...(modalProps.attrs || modalProps)
          }, {
            visible: this.visible
          }),
          $slots: {},
          on: Object.assign({}, {
            ok: () => {
              that.handleOk()
            },
            cancel: () => {
              that.handleClose()
            }
          })
        })
        const componentModel = componentProps && componentProps.model
        if (componentModel) {
          delete componentProps.model
        }
        componentProps = { ...componentProps, Watchmsg: this.msg }
        // eslint-disable-next-line no-mixed-operators
        const ComponentProps = Object.assign({}, componentModel && { model: componentModel } || {}, {
          ref: '_component',
          attrs: Object.assign({}, {
            ...((componentProps && componentProps.attrs) || componentProps),
            selfClose: () => {
              this.selfClose()
            },
            modalAllClose: () => {
              this.modalAllClose()
            }
          }),
          on: Object.assign({}, {
            ...((componentProps && componentProps.on) || componentProps)
          })
        })
        const configProps = Object.assign({}, {
          attrs: {
            locale: zhCN
          }
        })
        let myComs = {}
        if (FLAHISVUE) {
          var res = Vue.compile(component)
          myComs = {
            render: res.render,
            staticRenderFns: res.staticRenderFns
          }
        }
        // eslint-disable-next-line no-unreachable
        let ELEMENT = FLAHISVUE ? h(Modal, ModalProps, [h(myComs)]) : h(Modal, ModalProps, [h(configProvider, configProps, [h(component, ComponentProps)])])
        return ELEMENT
      }
    }

    var MyComponent = Vue.extend(componentObj)
    dialogInstance = new MyComponent({
      propsData: {
        msg: '' // 动态组件传参，用于弹窗自定义监听（变相实现watch）
      }
    }).$mount(dialogDiv)
    allDialogInstance.push(dialogInstance)
  }
  Object.defineProperty(Vue.prototype, '$dialog', {
    get: () => {
      return function () {
        dialog.apply(this, arguments)
      }
    }
  })
}
